package com.fintech.pangu.security.oauth2.sso.client.authentication;


import com.fintech.pangu.commons.jwt.JWTUtil;
import com.fintech.pangu.keyvault.KeyVaultObtain;
import com.fintech.pangu.security.authentication.handler.RedirectBySavedRequestParameterAuthenticationSuccessHandler;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.OAuth2Authentication;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * OAuth2 SSO Client 登录成功处理器
 * 构造用户信息JWT存入session，之后按照缓存请求的参数重定向
 */
@Data
public class GenerateJWTAuthenticationSuccessHandler extends RedirectBySavedRequestParameterAuthenticationSuccessHandler {

    private KeyVaultObtain keyVaultObtain;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // session中存入JWT
        OAuth2Authentication auth2Authentication = (OAuth2Authentication) authentication;
        String userName = (String) auth2Authentication.getPrincipal();
        String key = keyVaultObtain.getKey();
        String sysCode = request.getParameter("sysCode");
        Map<String, Object> userDetails = (Map<String, Object>) auth2Authentication.getUserAuthentication().getDetails();
        if (StringUtils.isNotEmpty(sysCode)) {
            userDetails.put("sysCode", sysCode);
        }
        String jwtToken = JWTUtil.generateToken(userName, key, -1, userDetails);
        request.getSession().setAttribute("userDetails", jwtToken);

        // 调用父类逻辑，按照缓存请求的参数重定向
        super.onAuthenticationSuccess(request, response, authentication);
    }

}
